import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/bean/attend_record_calendar_response_bean.dart';
import 'package:flutter/material.dart';

///考勤记录日历统计卡片
///
/// @author: zengxiangxi
/// @createTime: 3/16/21 11:31 AM
/// @specialDemand:
class AttendRecordCalendarStatisticsCardWidget extends StatelessWidget {
  ///具体信息
  final ValueNotifier<AttendRecordCalendarDataBean> dateInfoValueNotifier;

   AttendRecordCalendarStatisticsCardWidget(
      {Key key, this.dateInfoValueNotifier})
      : super(key: key);

   int all = 0;

  String type = UserRepository.getInstance().getType();

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: dateInfoValueNotifier,
      builder: (BuildContext context, AttendRecordCalendarDataBean dateInfoBean,
          Widget child) {
        if (!(dateInfoBean?.ruleFlg ?? true)) {
          return _toNoRuleWidget(dateInfoBean);
        }
        return Container(
          // height: 109,
          decoration: BoxDecoration(
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            borderRadius: BorderRadius.circular(8),
          ),
          margin: const EdgeInsets.only(left: 15,right: 15,bottom: 12 ),
          child: Column(
            children: [
          Container(
          padding: const EdgeInsets.only(top: 9),
          child: Row(
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(1.5),
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                ),
                width: 3,
                height: 14,
              ),
              SizedBox(width: 10.5),
              Text(
                "当月统计",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    fontSize: 15,
                    fontWeight: FontWeight.w600),
              ),
              Text(
                // " · 工作日${_day(dateInfoBean)}天",
                "${type=="00"||type=="02"?" · 工作日${_day(dateInfoBean)}天":""}",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    fontSize: 15),
              )
            ],
          ),
        ),
              SizedBox(height: 7,),
              Row(
                children: <Widget>[
                  Expanded(
                    child: _StatisticsItemWidget(
                      title: "正常",
                      statistics: _statisticsStr(dateInfoBean,"正常"),
                      day: dateInfoBean?.normalCnt,
                      dayColor: ThemeRepository.getInstance()
                          .getTextMainColor_D0E0F7(),
                    ),
                  ),
                  _toSplitLineWidget(),
                  Expanded(
                    child: _StatisticsItemWidget(
                      title: "异常",
                      statistics: _statisticsStr(dateInfoBean,"异常"),
                      day: dateInfoBean?.abnormalCnt,
                      // dayColor: ThemeRepository.getInstance().getMinorRedColor_F95355(),
                      dayColor: Color(0xFFFFB714),
                    ),
                  ),
                  _toSplitLineWidget(),
                  Expanded(
                    child: _StatisticsItemWidget(
                      title: "缺勤",
                      statistics: _statisticsStr(dateInfoBean,"缺勤"),
                      day: dateInfoBean?.absenceCnt,
                      dayColor: ThemeRepository.getInstance()
                          .getMinorRedColor_F95355(),
                    ),
                  ),
                  _toSplitLineWidget(),
                  Expanded(
                    child: _StatisticsItemWidget(
                      title: "加班",
                      statistics: _statisticsStr(dateInfoBean,"加班"),
                      day: dateInfoBean?.overtimeCnt,
                      dayColor: ThemeRepository.getInstance()
                          .getHintGreenColor_00C6C4(),
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  int _day(AttendRecordCalendarDataBean dateInfoBean){
    String monthNum = "22";
    int day = 0;
    DateTime _strTime = DateTime.now();
    if(dateInfoBean?.punchRecord!=null){
      _strTime = DateTime.parse(dateInfoBean?.punchRecord[0]?.date);
    }
    // int month = widget.dateInfoValueNotifier.value.punchRecord[0].date;
    for (var month = 1; month <= 12; month++) {
      // 年份，随便哪一年
      var year = _strTime.year;
      // var monnth = _strTime.month;
      // 计算下个月1号的前一天是几号，得出结果
      String dayCount = DateTime(year, month + 1, 0).day.toString();

      if(_strTime.month == month){
        monthNum = dayCount;
      }

    }
    day = int.parse(monthNum??"0")-(dateInfoBean?.restCnt??0);
    return day;
  }

  String _statisticsStr(AttendRecordCalendarDataBean dateInfoBean,String title,{bool barTow}){
    int leave = 0;
    int exception = 0;
    int absence = 0;
    int overTime = 0;
    dateInfoBean?.punchRecord?.forEach((element) {
      if(element?.isLeave() ?? false){
        leave = ++leave;
      }else if(element?.isException() ?? false){
        exception = ++exception;
      }else if(element?.isNotify() ?? false){
        absence = ++absence;
      }else if(element?.isOverTime() ?? false){
        overTime = ++overTime;
      }
    });
    if(title=="未刷脸缺勤"&&leave+absence!=0){
      all = 1;
    }
    if(leave+exception+absence+overTime!=0 && !(title=="未刷脸缺勤"||title=="")){//有规则，有异常情况
      all=1;
    }
    if(title=="正常" && leave!=0){
      return "（外出$leave天）,$all";
    }else if(title=="异常"&& exception!=0){
      return "" ",$all";
    }else if(title=="缺勤"&& absence!=0){
      return "（请假$absence天）,$all";
    }else if(title=="加班"&& overTime!=0){
      return "" ",$all";
    }else if(title=="未刷脸缺勤"&& absence!=0){
      return "（请假$absence天）,$all";
    }else{
      return "" ",$all";
    }
  }

  Widget _toNoRuleWidget(AttendRecordCalendarDataBean dateInfoBean) {
    return Container(
      // height: 96,
      decoration: BoxDecoration(
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        borderRadius: BorderRadius.circular(8),
      ),
      margin: const EdgeInsets.only(left: 15,right: 15,bottom: 20 ),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.only(top: 10,bottom: 6),
            child: Row(
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(1.5),
                    color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  ),
                  width: 3,
                  height: 14,
                ),
                SizedBox(width: 10.5),
                Text(
                  "当月统计",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                      fontSize: 15,
                     fontWeight: FontWeight.w600),
                ),
                Text(
                  // " · 工作日${_day(dateInfoBean)}天",
                  "${type=="00"||type=="02"?" · 工作日${_day(dateInfoBean)}天":""}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                      fontSize: 15),
                )
              ],
            ),
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: _StatisticsItemWidget(
                  title: "已刷脸",
                  statistics: _statisticsStr(dateInfoBean,""),
                  day: dateInfoBean?.faceDayCnt,
                  dayColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                ),
              ),
              _toSplitLineWidget(),
              Expanded(
                child: _StatisticsItemWidget(
                  title: "未刷脸",
                  statistics: _statisticsStr(dateInfoBean,""),
                  day: dateInfoBean?.unFaceDayCnt,
                  dayColor: ThemeRepository.getInstance().getMinorRedColor_F95355(),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _toSplitLineWidget() {
    return Container(
      width: 1,
      height: 40,
      // margin: const EdgeInsets.only(bottom: 20),
      decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getLineColor_3A3F50()),
    );
  }
}

/// 统计项组件
///
/// @author: zengxiangxi
/// @createTime: 3/16/21 1:42 PM
/// @specialDemand:
class _StatisticsItemWidget extends StatelessWidget {
  final String title;

  final int day;

  final Color dayColor;

  final String statistics;

  //当打卡数据为0时默认颜色
  final Color emptyColor;
  //AttendRecordCalendarTitleBarWidget(),

  const _StatisticsItemWidget(
      {Key key, this.title, this.day, this.dayColor, this.emptyColor, this.statistics})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          // Spacer(flex: 11),
          Text(
            title ?? "",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color:
                  ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
              fontSize: 13,
            ),
          ),
          // Spacer(flex: 4),
          Container(
            // padding: const EdgeInsets.only(top: 4),
            height: statistics?.split(",")[1]?.toString() != "0" ? 21 :31,
            child: Center(
              child: Text(
                day == null || day <= 0 ? "-" : "$day天",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: day == null || day <= 0
                        ? ThemeRepository.getInstance()
                            .getDefaultGrayColor_FF5E687C()
                        : dayColor,
                    fontSize: 14,
                    fontWeight: FontWeight.w600),
              ),
            ),
          ),
          if(statistics?.split(",")[1]?.toString() == "0")
          SizedBox(height: 10,),
          // Spacer(flex: 10),
          if(statistics?.split(",")[1]?.toString() != "0")
          Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                height: 25,
                padding: const EdgeInsets.only(bottom: 12),
                  child: Text(
                    statistics?.split(",")[0]?.toString() ?? "",
                style: TextStyle(
                    color:
                    dayColor,
                    fontSize: 10),
              )),
            ],
          ),
        ],
      ),
    );
  }
}
